package textviewer.main;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class GUIInternetBookSelection extends Activity{
	private Config myconfig;
	private int listenOnID;
	private ArrayList<String> bookname = new ArrayList<String>();
	private ArrayList<String> booktitle = new ArrayList<String>();
	private ArrayList<String> bookurl = new ArrayList<String>();
	private ArrayList<String> bookid = new ArrayList<String>();
	private int analysis_mode;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       ArrayList<String> server_names = Utility.return_server_list_name();
       ArrayList<String> server_urls = Utility.return_server_list_url();
        Bundle extras = getIntent().getExtras();
        listenOnID = extras.getInt("listenOnID", 0);
        analysis_mode=extras.getInt("analysis_mode", 1);
      //  listen_onID2Forum=extras.getBoolean("listen_onID2Forum", false);
        String encode_phase=extras.getString("encode_phase");
        
        ScrollView scllview = new ScrollView(this);
        
        ScrollView.LayoutParams scllview_param = new ScrollView.LayoutParams(
        		ViewGroup.LayoutParams.FILL_PARENT,
        		ViewGroup.LayoutParams.FILL_PARENT);
        scllview.setBackgroundColor(Color.WHITE);
        myconfig = new Config(this);
        scllview.setBackgroundDrawable(myconfig.return_bg());
        LinearLayout Llay = new LinearLayout(this);
        LinearLayout.LayoutParams Llay_param = new LinearLayout.LayoutParams(
        		ViewGroup.LayoutParams.FILL_PARENT,
        		ViewGroup.LayoutParams.FILL_PARENT);
        Llay.setOrientation(LinearLayout.VERTICAL);
        
        if(analysis_mode==1&&listenOnID==0)
        {
        	TCPGatherBookSelection tcpgather = new TCPGatherBookSelection(server_urls.get(listenOnID),this);
	        //mode 1, Get the latest updates
	        boolean ConnectedOrNot = tcpgather.connect_toTarget();
	       if(ConnectedOrNot)
	       {
		       	bookname=tcpgather.Getbookname();
		    	booktitle=tcpgather.Getbooktitle();
		    	bookurl=tcpgather.Getbookurl();
		    	bookid=tcpgather.Getbookid();
		        ArrayList<LinearLayout> list_layout = new ArrayList<LinearLayout>();
		        for(int i=0;i<bookname.size();i++)
		        {
		     	   LinearLayout tmpLayout = new LinearLayout(this);
		            LinearLayout.LayoutParams tmpLayout_param = new LinearLayout.LayoutParams(
		            		ViewGroup.LayoutParams.FILL_PARENT,
		            		ViewGroup.LayoutParams.WRAP_CONTENT);
		            TextView tmp_txtview = new TextView(this);
		            tmp_txtview.setText(bookname.get(i));
		            tmp_txtview.setTextColor(Color.BLACK);
		            tmp_txtview.setTextSize(TypedValue.COMPLEX_UNIT_SP,(float)21);
		            PanelOnTouchListener potl =  new PanelOnTouchListener(tmp_txtview);
		            tmpLayout.setClickable(true);
		            tmpLayout.setOnTouchListener(potl);
		        	InternetBookClickListener click_listener = new InternetBookClickListener(this,bookname.get(i),this.bookurl.get(i),this.bookid.get(i));
		        	tmpLayout.setOnClickListener(click_listener);
		        	tmpLayout.addView(tmp_txtview);
		     	   Llay.addView(tmpLayout,tmpLayout_param);
		        }
	    	   Utility.quick_dialog("Connected successfully", this);
	       }
	       else
	       {
	    	   Utility.quick_dialog("Please check your internet connection.", this);
	       }
        }
        else if(analysis_mode==2&&listenOnID==0)
        {
			TCPGather mytcpgather = new TCPGather("http://www.booksky.org/Search.aspx?BookName="+encode_phase+"&SearchType=ForBookName");
			if(mytcpgather.AskForHtml("utf-8"))
			{
				ArrayList<String> html_result = mytcpgather.GetTheResult();
				ArrayList<String> bookid = new ArrayList<String>();
				ArrayList<String> bookname = new ArrayList<String>();
				ArrayList<String> bookauthor = new ArrayList<String>();
				ArrayList<Boolean> bookactive = new ArrayList<Boolean>();
				for(int i=0;i<html_result.size();i++)
				{
					//
					if(html_result.get(i).matches(".*书名：.*作者：.*"))
					{
						bookid.add(html_result.get(i).replaceFirst(".*[Bb][Oo][Oo][Kk][Ii][Dd]=", "").replaceFirst("\">.*</[aA]>.*[Hh][Rr][Ee][Ff].*", ""));
						bookname.add(html_result.get(i).replaceFirst(".*<[Aa] *[Hh][Rr][Ee][Ff].*> *<[Bb]> *", "").replaceFirst(" *</[Bb]> *</[Aa]>.*", ""));
						bookauthor.add(html_result.get(i).replaceFirst(".*<[Aa] [Hh][Rr][Ee][Ff].*<[Aa] *[Hh][Rr][Ee][Ff].*[Aa][Uu][Tt][Hh][Oo][Rr].*\"> *", "").replaceFirst("</[aA]>.*", ""));
						bookactive.add(html_result.get(i).replaceFirst(".*<[Aa] *[Hh][Rr][Ee][Ff].*\">.*<[Aa] *[Hh][Rr][Ee][Ff].*\">.*</[Aa]>", "").replaceFirst("</[Tt][Dd]>", "").contains("自动查找"));
						System.out.println("123"+bookname.get(bookname.size()-1));
					}
					
					//BookID=
				}
				for(int i=0;i<bookname.size();i++)
				{
					this.bookname.add(bookname.get(i));
					this.bookid.add(bookid.get(i));
					this.bookurl.add("http://www.booksky.org/BookDetail.aspx?BookID="+bookid.get(i));
			     	   LinearLayout tmpLayout = new LinearLayout(this);
			            LinearLayout.LayoutParams tmpLayout_param = new LinearLayout.LayoutParams(
			            		ViewGroup.LayoutParams.FILL_PARENT,
			            		ViewGroup.LayoutParams.WRAP_CONTENT);
			            TextView tmp_txtview = new TextView(this);
			            tmp_txtview.setText(bookname.get(i));
			            tmp_txtview.setTextColor(Color.BLACK);
			            tmp_txtview.setTextSize(TypedValue.COMPLEX_UNIT_SP,(float)21);
			            PanelOnTouchListener potl =  new PanelOnTouchListener(tmp_txtview);
			            tmpLayout.setClickable(true);
			            tmpLayout.setOnTouchListener(potl);
			        	InternetBookClickListener click_listener = new InternetBookClickListener(this,bookname.get(i),this.bookurl.get(i),this.bookid.get(i));
			        	tmpLayout.setOnClickListener(click_listener);
			        	tmpLayout.addView(tmp_txtview);
			     	   Llay.addView(tmpLayout,tmpLayout_param);
				}
			}
        }
        else if(listenOnID==1)
        {
        	
        	//String cookie_data =Utility.site2_cookieData();
            String tcp_dest=Utility.return_webSite2Root()+"index.php";
            TCPGather cookie_tcpgather = new TCPGather(Utility.return_webSite2Root()+"logging.php?action=login&loginsubmit=true&formhash=27a2eb92&cookietime=2592000&loginfield=username&username=eg_ckcaf&password=chung1234");
            cookie_tcpgather.GetTheCookie();
           // cookie_tcpgather.setSite2PostValue("27a2eb92", "2592000", "username", "eg_ckcaf", "chung1234");
            cookie_tcpgather.AskForHtml();
            ArrayList<String> cookie_html_result = cookie_tcpgather.GetTheResult();
            System.out.println("size"+cookie_html_result.size());;
            /*
            for(int i=0;i<cookie_html_result.size();i++)
            {
            	System.out.println( cookie_html_result.get(i));
            }
            */

        	//String tcp_dest="http://www.dk101.com/Discuz/viewthread.php?tid=195773&extra=page%3D1";
        	TCPGather tcpgather = new TCPGather(tcp_dest,cookie_tcpgather.getBackCookieStr());
            tcpgather.AskForHtml();
            ArrayList<String> html_result = tcpgather.GetTheResult();
        	/*
				<input type="hidden" name="formhash" value="27a2eb92" />
		<input type="hidden" name="cookietime" value="2592000" />
		<input type="hidden" name="loginfield" value="username" />
		<input type="text" id="username" name="username" size="15" maxlength="40" tabindex="1" value="用戶名" onclick="this.value = ''" />
		<input type="password" id=" */
            
         //   Utility.quick_dialog(String.valueOf(html_result.size()), this);
            ArrayList<String> forum_name = new ArrayList<String>();
            ArrayList<String> forum_url = new ArrayList<String>();
           boolean started_capture = false;
            for(int i=0;i<html_result.size();i++)
            {
            	if(html_result.get(i).contains("文學專區"))
            	{
            		started_capture=true;
            	}
            	else if(html_result.get(i).contains("緣份天地"))
            	{
            		started_capture=false;
            	}
            	else if(started_capture==true)
            	{
            		//if(html_result.get(i).matches(".*<[Tt][Hh] *[Cc][Ll][Aa][Ss][Ss]=.{1}[nn][Ee][Ww].{1}>.*"))
            		if(html_result.get(i).matches(".*<[Hh]2>.*<[aA] *[Hh][Rr][Ee][Ff].*>.*</[Aa]>.*</[Hh]2>.*"))
            		{
            			forum_url.add(html_result.get(i).replaceFirst(".*<[Hh]2>.*<[aA] *[Hh][Rr][Ee][Ff] *= *\"","").replaceFirst("\">.*</[aA]> *</[Hh]2>", ""));
            			forum_name.add(html_result.get(i).replaceFirst(".*<[Hh]2>.*<[aA] *[Hh][Rr][Ee][Ff] *=.*\">","").replaceFirst("</[aA]>.*", ""));
            		}
            	}

            }
            for(int i=0;i<forum_name.size();i++)
            {
		     	   LinearLayout tmpLayout = new LinearLayout(this);
		            LinearLayout.LayoutParams tmpLayout_param = new LinearLayout.LayoutParams(
		            		ViewGroup.LayoutParams.FILL_PARENT,
		            		ViewGroup.LayoutParams.WRAP_CONTENT);
		            TextView tmp_txtview = new TextView(this);
		            tmp_txtview.setText(forum_name.get(i));
		            tmp_txtview.setTextColor(Color.BLACK);
		            tmp_txtview.setTextSize(TypedValue.COMPLEX_UNIT_SP,(float)21);
		            PanelOnTouchListener potl =  new PanelOnTouchListener(tmp_txtview);
		            tmpLayout.setClickable(true);
		            tmpLayout.setOnTouchListener(potl);
		        	InternetBookClickListener click_listener = new InternetBookClickListener(cookie_tcpgather.getBackCookieStr(),this,forum_name.get(i),forum_url.get(i));
		        	tmpLayout.setOnClickListener(click_listener);
		        	tmpLayout.addView(tmp_txtview);
		     	   Llay.addView(tmpLayout,tmpLayout_param);
            }

            
            
        }
        
       // Llay.addView(txtview);
        //Utility.quick_dialog(String.valueOf(listenOnID), this);
        scllview.addView(Llay, Llay_param);

        this.setTitle(server_names.get(listenOnID)+": Book Selection");

        this.setContentView(scllview, scllview_param);
       // Thread tcpgather_thread = new Thread(tcpgather);
       // tcpgather_thread.start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) { 
    	menu.add(0, 0, 0, "Find a book").setIcon(android.R.drawable.ic_menu_search);
    	menu.add(0, 1, 1, "Return to BookShelf").setIcon(android.R.drawable.ic_menu_revert); 
    	
       menu.add(0, 3, 3, "Setting").setIcon(android.R.drawable.ic_menu_preferences);
       return super.onCreateOptionsMenu(menu); 
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	if(item.getItemId()==0)
    	{
    		showDialog(DIALOG_TEXT_ENTRY);
    	}
    	else if(item.getItemId()==1)
    	{
    		Intent int_ent = new Intent(this, GUIBookShelfBkSelect.class);
    		this.startActivity(int_ent);
    		finish();
    	}
    	else if(item.getItemId()==3)
    	{
    		Intent int_ent = new Intent(this, GUIConfig.class);
    		this.startActivity(int_ent);
    	}
    	return super.onOptionsItemSelected(item); 
    }
    private static final int DIALOG_TEXT_ENTRY = 7;
    @Override   
    protected Dialog onCreateDialog(int id) {
    	switch(id){
    case DIALOG_TEXT_ENTRY:
    	// This example shows how to add a custom layout to an AlertDialog
    	LayoutInflater factory = LayoutInflater.from(this);
    	final EditText search_box = new EditText(this);
    	final View textEntryView = search_box;
    	return new AlertDialog.Builder(GUIInternetBookSelection.this)
    	//.setIconAttribute(android.R.attr.alertDialogIcon)
    	.setTitle("Search Book")
    	.setView(textEntryView)
    	.setPositiveButton("ok", new DialogInterface.OnClickListener() {
    		public void onClick(DialogInterface dialog, int whichButton) {
    			/* User clicked OK so do some stuff */
    				String tmp_encrypted_str = search_box.getText().toString();
    				//Utility.quick_dialog(search_box.getText().toString(), GUIInternetBookSelection.this);
    				search_box.setText("");
    				if(tmp_encrypted_str.equals(""))
    				{
    					Utility.quick_dialog("You must search something.", GUIInternetBookSelection.this);
    					return;
    				}
    				try {
    					
						String encode_phase=URLEncoder.encode(tmp_encrypted_str,"utf-8");
						Intent int_ent = new Intent(GUIInternetBookSelection.this, GUIInternetBookSelection.class);
						int_ent.putExtra("encode_phase",encode_phase );
						int_ent.putExtra("analysis_mode", 2);
						int_ent.putExtra("listenOnID", listenOnID);
//listenOnID
						GUIInternetBookSelection.this.startActivity(int_ent);
//analysis_mode
						
						//Utility.quick_dialog(encode_phase, GUIInternetBookSelection.this);
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						//e.printStackTrace();
					}
    			} 
    		})
    		.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialog, int whichButton) {
    				search_box.setText("");
    				/* User clicked cancel so do some stuff */
    				} 
    			})
    			.create();
    	}
    	return null;
    	}
    	
}
